package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import cn.tedu._03vehicle.mapper.UserMapper;
import cn.tedu._03vehicle.pojo.dto.UserLoginParam;
import cn.tedu._03vehicle.pojo.dto.UserRegParam;
import cn.tedu._03vehicle.pojo.entity.User;
import cn.tedu._03vehicle.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@RestController
@Tag(name = "01-用户管理模块")
@RequestMapping("/v1/user/")
public class UserController {
    //自动装配
    @Autowired
    private UserMapper userMapper;

    /**
     * 1.注册功能
     */
    @PostMapping("reg")
    @Operation(summary = "注册")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody @Validated UserRegParam userRegParam){
        log.debug("userRegParam = " + userRegParam);
        /*
            1.接收客户端传递的数据[已完成];
            2.校验数据合法性[暂时不做];
            3.确认用户名是否被占用[SELECT接口];
              SELECT COUNT(*) FROM user WHERE username = ?;
              3.1 被占用: return 结束;
              3.2 未被占用: 将用户数据保存到数据表[INSERT接口],return 结束!
         */
        String username = userRegParam.getUsername();
        int count = userMapper.selectUserByUsername(username);
        if (count > 0){ //被占用
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        //未被占用
        User user = new User();
        BeanUtils.copyProperties(userRegParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        log.debug("user = " + user);
        int i = userMapper.insertUser(user);
        if (i > 0){ //注册成功
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    /**
     * 2.登录功能
     */
    @PostMapping("login")
    @Operation(summary = "登录")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("userLoginParam = " + userLoginParam);
        // SELECT id,username FROM user WHERE username=? AND password=?
        /*
            userVO: {"id":1,"username":"xxx"}
            userVO: null
         */
        UserVO userVO = userMapper.selectUserByUsernameAndPassword(userLoginParam);
        if (userVO == null){//用户名或密码错误
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        //登录成功,保存用户信息到session会话中
        session.setAttribute("user", userVO);
        return JsonResult.ok(userVO);
    }

    /**
     * 3.获取当前用户功能
     */
    @GetMapping("currentUser")
    @Operation(summary = "获取当前用户")
    @ApiOperationSupport(order = 30)
    public JsonResult currentUser(HttpSession session){
        //从session会话中获取用户标识
        UserVO userVO = (UserVO) session.getAttribute("user");
        /*
            服务端返回: response: {"state":2000,"message":"操作成功", "data": userVO}
            前端工程师:
            response.data:{"state":2000,"message":"操作成功", "data": userVO}
            response.data.data: userVO
            if (response.data.data == null){
                router.push("/login"); //跳转到登录页面
            }else{
                //从userVO中获取用户名
                router.push("/index.html"); //以登录的状态跳转到首页
            }
         */
        return JsonResult.ok(userVO);
    }

    /**
     * 4.退出登录功能
     *   4.1 登录成功;
     *   4.2 获取当前用户[获取成功];
     *   4.3 退出登录;
     *   4.4 获取当前用户[获取不到];
     */
    @GetMapping("logout")
    @Operation(summary = "退出登录")
    @ApiOperationSupport(order = 40)
    public void logout(HttpSession session){
        //删除session会话中的用户标识
        session.removeAttribute("user");
    }

    /**
     * 5.注册功能:用于演示HttpServletRequest的用法
     *   请求方法:GET
     *   请求路径: /v1/user/reg2
     *   请求参数: username, password, email, phone
     *   http://localhost:8080/v1/user/reg2?username=xxx&password=123456&email=yyy&phone=13111112222
     */
    @GetMapping("reg2")
    public JsonResult reg2(HttpServletRequest request){
        //1.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        System.out.println(username + password + email + phone);
        //2.获取客户端的IP地址
        String addr = request.getRemoteAddr();
        //3.获取请求方法
        String method = request.getMethod();
        //4.获取请求头中的Cookie
        Cookie[] cookies = request.getCookies();
        //5.获取当前请求的会话信息
        HttpSession session = request.getSession();

        return JsonResult.ok();
    }
}











